package com.service.imp;

import com.common.Base;
import com.common.Result;
import com.entity.Topic;
import com.repository.TopicRepository;
import com.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author：Luohuiyong
 * @Description:
 * @Date: Created in 11:06 2019/1/9
 */
@Service
public class TopicServiceImp implements TopicService {

    @Autowired
    private TopicRepository topicRepository;

    @Override
    public Topic findOne(int id){
        Optional<Topic> optionalTopic = topicRepository.findById(id);
        return optionalTopic.get();
    }

    /**
     * 新增一个实体
     * @param topic
     * @return
     */
    @Transactional
    @Override
    public Result create(Topic topic){
        topic.setCreatedAt(new Date());
        topicRepository.save(topic);

        return Base.success();
    }

    /**
     * 分页查询数据
     * @param topic
     * @return
     */
    @Override
    public Result index(Topic topic){

        Pageable pageable = new PageRequest(topic.getPage(),topic.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Topic> page = topicRepository.findAll(pageable);
        long total = topicRepository.count();
        long maxPage = total/topic.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }

    /**
     * 查询推荐专题数据
     * @param topic
     * @return
     */
    @Override
    public Result recommend(Topic topic){

        List<Topic> resList = topicRepository.findByIsRecommend(1);

        return Base.success(resList);
    }

    /**
     * 搜索专题数据
     * @param topic
     * @return
     */
    @Override
    public Result search(Topic topic){
        if(StringUtils.hasText(topic.getName())){
            Pageable pageable = new PageRequest(topic.getPage(),topic.getPageSize(),Sort.Direction.DESC,"createdAt");
            String name = "%" + topic.getName() + "%";
            Page<Topic> page = topicRepository.findAllByNameLike(name,pageable);
            long total = topicRepository.countByNameLike(name);
            long maxPage = total/topic.getPageSize();

            return Base.success(page.getContent(),total,maxPage);
        }

        return null;
    }


}
